<template>
  <div class="main-container">
    <el-row class="layout-container-demo" style="height: 576px;">
      <el-col :span="10">
        <!--             <el-scrollbar> -->
        <el-menu ref="menuRef" :default-openeds="[]" background-color="#FAFCFF">
          <el-menu-item index="-1" style="display: none;"></el-menu-item>
          <el-menu-item index="0" @click="menuButtonClick(0)"><el-icon>
              <setting />
            </el-icon>DeadSplit Setting<span class="bossname">{{ $deadSplitData.value.bosses[$deadSplitData.value.currentBoss].name==='' ? 'Boss#'+($deadSplitData.value.currentBoss+1) : $deadSplitData.value.bosses[$deadSplitData.value.currentBoss].name}}</span></el-menu-item>
          <DsItem style="padding: 1px; height: 460px;" ref="dsItemRef" @edit="openEditItem" />
          <el-menu-item index="1" @click="menuButtonClick(1)"><el-icon>
              <Plus />
            </el-icon>New Item</el-menu-item>
        </el-menu>
        <!--             </el-scrollbar> -->
      </el-col>
      <el-col :span="14">
        <el-container style="height: 576px;">
          <el-header style="text-align: right; font-size: 12px">

            <div class="toolbar">
              <el-dropdown trigger="click">
              <div class="export-btn" style="margin-right: 12px;">
                <el-icon style="margin-right: 8px; margin-top: 1px; vertical-align: middle;">
                  <Download />
                </el-icon>
                <span>Export</span>
                
              </div>
                  <template #dropdown>
                    <el-dropdown-menu>
                    <el-dropdown-item @click="saveProject">Save Project</el-dropdown-item>
                    <el-dropdown-item @click="exportXML">Export XML</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <el-dropdown trigger="click">
              <div class="export-btn"  style="margin-right: 12px;">
                <el-icon style="margin-right: 8px; margin-top: 1px">
                  <Upload />
                </el-icon>
                <span>Inport</span>
              </div>
                  <template #dropdown>
                    <el-dropdown-menu>
                    <el-dropdown-item @click="loadProject">Load Project</el-dropdown-item>
                    <el-dropdown-item @click="loadXML">Load XML</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <div class="export-btn" @click="diagSetting.openSettings()">
                <el-icon style="margin-right: 8px; margin-top: 1px">
                  <Setting />
                </el-icon>
                <span>Setting</span>
              </div>
              
              <!-- <el-dropdown>
                            <el-icon style="margin-right: 8px; margin-top: 1px">
                            <setting />
                            </el-icon>
                            <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item>View</el-dropdown-item>
                                <el-dropdown-item>Add</el-dropdown-item>
                                <el-dropdown-item>Delete</el-dropdown-item>
                            </el-dropdown-menu>
                            </template>
</el-dropdown>
<span>Setting</span> -->
            </div>
          </el-header>
          <el-main>
            <el-scrollbar>
              <Buttons v-if="show == 0 || (show == 2 && show_==0)" @handleClick="videoButtonClick" />
              <VideoPlayer v-else-if="show==1" :videoSource="url" @exit="show = 0" @add-attack="

                              // @ts-ignore: Object is possibly 'null'
                              menuRef.updateActiveIndex(1)
                              menuButtonClick(1)
                              // @ts-ignore: Object is possibly 'null'
                              diagItem.setTime($event);
                            " />
              <YoutubePlayer :w="resolution.width" :h="resolution.height" v-if="show == 2" v-show="show_ == 1" :videoId
                @ytbPlayerReady="show_ = 1" />
            </el-scrollbar>
          </el-main>
        </el-container>
      </el-col>
    </el-row>
    <OpenVideoDialog ref="diagFunction" @sbmt="runPlayer" />
    <ItemDialog ref="diagItem" @add="handleAddItem" @edit="handleEditItem" @close="closeItem" />
    <GlobalSetting ref="diagSetting" />
    <DsSetting ref="dsSettingRef" @close="closeItem" @updateBossData="handleUpadteData"/>
  </div>
</template>

<script lang="ts" setup>
//@ts-nocheck
import { computed, Reactive, ref,getCurrentInstance } from 'vue'
import { Setting, Plus, Download, Upload } from '@element-plus/icons-vue'

import { invoke } from '@tauri-apps/api/core';
//import type { ElMessage } from 'element-plus';
import { exists, mkdir, readFile, readTextFile, writeTextFile } from '@tauri-apps/plugin-fs';
import {open} from '@tauri-apps/plugin-dialog';

import { basename, dirname } from '@tauri-apps/api/path';
//import { ElMessage } from 'element-plus';
//import { ElMessage, ElMessageBox } from 'element-plus';






const $global=getCurrentInstance()?.appContext.config.globalProperties;
// 读取二进制文件（比如图片）
async function loadVideo(directory: string) {
  try {
    const Data = await readFile(directory);
    // 创建Blob对象，用于显示图片
    const blob = new Blob([Data]);
    const Url = URL.createObjectURL(blob);
    return Url;
  } catch (error) {
    console.error('加载失败:', error);
    return null;
  }
}
const handleUpadteData=()=>{
  const list=dsItemRef.value.getList();
  $global.$bossData.value[$global.$deadSplitData.value.currentBoss]=[...list];
  dsSettingRef.value.saveSettings()
  dsItemRef.value.getPromptGroup();

}

// 创建响应式变量记录窗口尺寸
/* const windowSize = ref({
  width: window.innerWidth,
  height: window.innerHeight
}); */

/* // 处理窗口尺寸变化的函数
const handleResize = () => {
  windowSize.value.width = window.innerWidth;
  windowSize.value.height = window.innerHeight;
};

// 监听窗口 resize 事件
onMounted(() => {
  window.addEventListener('resize', handleResize);
});

// 组件卸载时移除监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
}); */

// 基于响应式的 windowSize 计算分辨率
const resolution = computed(() => ({
  width: String(window.innerWidth * 12.6 / 24),
  height: String(window.innerHeight * 12.6 / 24)
}));
/* watch(resolution,()=>{
  console.log("aaaaaa")  
},
  { deep: true }) */

//const cookie = $global.$globalSetting.value.bilibiliCookie;
//temp
//cookie.value="testcookie=1; enable_web_push=DISABLE; buvid_fp_plain=undefined; is-2022-channel=1; buvid3=1F919D8D-00BC-7671-617B-46B5DEBC43C175357infoc; b_nut=1739858975; _uuid=FA13810101-BFB9-E237-8ADE-3CC16BE82FD985387infoc; hit-dyn-v2=1; enable_feed_channel=ENABLE; LIVE_BUVID=AUTO3117429673347761; rpdid=0zbfvU9x0I|mYt7cEB5|4gS|3w1TXs8k; dy_spec_agreed=1; header_theme_version=OPEN; theme-tip-show=SHOWED; theme-avatar-tip-show=SHOWED; theme-switch-show=SHOWED; DedeUserID=524942781; DedeUserID__ckMd5=db92d84561d03bdd; buvid4=0492D42B-AC09-99B8-6C75-A7DCBC8D0C7B69187-024021905-CUpCsmFdyYidKsDLXptAQ9XbAD2kIVcz+j4hOaGZxl74Ctxj4c3nH5uwCroZYdD+; fingerprint=a628eebaa764352b1e39155741fea9db; CURRENT_QUALITY=80; buvid_fp=a628eebaa764352b1e39155741fea9db; SESSDATA=f99d8a5d%2C1774668304%2C9dfc2%2A92CjCnyg24FvX3vy7EjQ5hV-FbNK47ikzDfcMKgbZhciwQoNppTQqnVks4hTDZikTvhUkSVnMtWFZrcGdyOVMyWmM5M2xJRXVVSTh2aWpRcXo2a3F5MnZoUFBJc2V5RWJrMjNvdGNVTWhmaUZVdUIyUDZubVdUUDkyLXp1VnBpcER5OS1HeFhleDFRIIEC; bili_jct=7795a6c84572ec1c6bfab22b6782f986; sid=4tgkmqor; PVID=1; bmg_af_switch=1; bmg_src_def_domain=i0.hdslb.com; home_feed_column=5; browser_resolution=1526-1044; bili_ticket=eyJhbGciOiJIUzI1NiIsImtpZCI6InMwMyIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NjA0Mjk5NDQsImlhdCI6MTc2MDE3MDY4NCwicGx0IjotMX0.9EhIV3hWirjeeKL4OA0VyH0XZNnu_CnWs_m9avemMTU; bili_ticket_expires=1760429884; CURRENT_FNVAL=2000; b_lsid=264E9A6D_199D338F001; bp_t_offset_524942781=1122476719123464192"
const diagFunction = ref();
const url = ref("");
const videoId = ref("");
const show_ = ref(0);
const show = ref(0);//0,按钮，1，bili，2，youtube，3，本地
const dsItemRef = ref(null);
const diagSetting = ref(null);
const menuRef = ref(null);
const diagItem = ref(null);
const dsSettingRef = ref(null);
const videoButtonClick = (type: string) => {
  if (type === 'youtube') {
    //@ts-ignore
    ElMessage.error("技术原因此部分暂时无法实现...")
    return
  }
  diagFunction.value.openDialog(type);

}
interface Form {
  iframe: string,
  yid: string,
  directory: string
}
const runPlayer = (type: string, form: Reactive<Form>) => {
  if (type == "bili") {
    /* url.value=form.iframe
    show.value=1 */
    invoke("get_bili_url", {
      iframe: form.iframe,//"32727894983",
      cookie: $global.$globalSetting.value.bilibiliCookie,
    }).then((resp: any) => {
      if (resp.code == 0) {
        url.value = resp.url
        show.value = 1
      }
      // @ts-ignore:Cannot find name 'ElMessage'.
      else ElMessage.error(resp.message)
    }).
    catch((err)=>{
      // @ts-ignore:Cannot find name 'ElMessage'.
      ElMessage.error(err)
    })
  }
  else if (type == "youtube") {
    videoId.value = form.yid
    show.value = 2
  }
  else if (type == "local") {
    loadVideo(form.directory).then((resp) => {
      if (resp !== null) {
        url.value = resp
        show.value = 1
      }
      // @ts-ignore:Cannot find name 'ElMessage'.
      else ElMessage.error("读取文件失败")
    }).catch((error) => {
      // @ts-ignore:Cannot find name 'ElMessage'.
      ElMessage.error("读取文件失败" + error)
    })

  }
}
interface AttackItem {
  beginTime: number,
  name: string,
  id: number,//自动指定
  icon: string,
  delay: number,
  elements: AttackItem[]
}

const menuButtonClick = (i: number) => {
  if (i === 1) {
    // @ts-ignore: Object is possibly 'null'
    diagItem.value.dialogFormVisible = true;
  }
  else if (i === 0) {
    // @ts-ignore: Object is possibly 'null'
    dsSettingRef.value.open();
  }
}
const openEditItem = (obj: AttackItem) => {
  // @ts-ignore: Object is possibly 'null'
  diagItem.value.title = "Edit Attack";
  // @ts-ignore: Object is possibly 'null'
  diagItem.value.dialogFormVisible = true;

  // @ts-ignore: Object is possibly 'null'
  diagItem.value.setAll(obj);
  //console.log(obj)
}
const closeItem = () => {

  // @ts-ignore: Object is possibly 'null'
  menuRef.value.updateActiveIndex(-1)

}
const handleAddItem = (obj: AttackItem) => {
  // @ts-ignore: Object is possibly 'null'
  menuRef.value.updateActiveIndex(-1)
  // @ts-ignore: Object is possibly 'null'
  dsItemRef.value.addItem(obj);
  //menuRef.activeIndex=null
  }
const handleEditItem=(obj:AttackItem)=>{
  // @ts-ignore: Object is possibly 'null'
  dsItemRef.value.updateItem(obj);
}
const saveProject=async()=>{
  if ($global.$deadSplitData.value.title==''){
    ElMessage.error("Please set fangame title in deadsplit setting")
    return
  }
  if ($global.$globalSetting.value.projectPath==''){
    ElMessage.error("Please set project path in global setting")
    return
  }
  const configDirPath = $global.$globalSetting.value.projectPath+"\\project";
  const configFilePath = `${configDirPath}\\${$global.$deadSplitData.value.title}.json`;
  $global.$bossData.value[$global.$deadSplitData.value.currentBoss]=[...dsItemRef.value.getList()];
  const projectData={...$global.$deadSplitData.value,bossData:$global.$bossData.value,autoIncreament:$global.$autoIncreament.value};
  ElMessageBox.confirm(`Save project as \"${configFilePath}\"? 同名项目将被覆盖`).then(async () => {
    try {
    if (await exists(configFilePath)) {
        await writeTextFile(configFilePath, JSON.stringify(projectData, null, 2));
    }
    else{
        if (!await exists(configDirPath)) {
          await mkdir(configDirPath, { recursive: true });
        }
      await writeTextFile(configFilePath, JSON.stringify(projectData, null, 2));
    }
    
    
    ElMessage.success(`设置已保存`);
  } catch (error) {
    console.error('保存设置失败:', error);
    ElMessage.error(`保存设置失败: ${error}`);
  }
  })
  
}
const loadProject=async()=>{
  
  const file = await open({
    multiple: false,
    directory: false,
  });
  const {autoIncreament,bossData,...rest} =JSON.parse(await readTextFile(file));
  //console.log(data)

  $global.$deadSplitData.value=rest;
  $global.$bossData.value=bossData;
  $global.$autoIncreament.value=autoIncreament;
  dsItemRef.value.getPromptGroup();
  
  
}
const exportXML=async()=>{
  $global.$bossData.value[$global.$deadSplitData.value.currentBoss]=[...dsItemRef.value.getList()];
  const data={...$global.$deadSplitData.value,bossData:$global.$bossData.value};
  const filename=await basename(data.dtFile).catch(() => {
    return
  })
  ;;
  const dir=await dirname(data.dtFile).catch(() => {
    return
  })
  ;
  if (!dir || !filename){
    ElMessage.error("Game DeathTime/SaveFile path invalid")
    return
  }
  console.log(dir)
  const part_1=
`<?xml version=\"1.0\" encoding=\"utf-16\"?>
<Fangame title=\"${data.title}\">
  <AddressSpace>
    <RoomId type=\"fixed\" valueType=\"int32\">${data.roomAddress}</RoomId>
  </AddressSpace>
  <SaveDetector fileName=\"${dir}\">
    <DeathDetector type=\"file\" name=\"${filename}\" offset=\"12\"/>
  </SaveDetector>
`
  let part2=''
  const bosses=data.bosses;
  const bossData=data.bossData
  for (let i=0;i<bosses.length;i++){
    const boss=bosses[i];
    part2+=boss.name!==''?`   <Boss name=\"${boss.name}\">\n`:`   <Boss name=\"boss#${i}\">\n`
    part2+=boss.preroomId!==''?`    <BossArea roomId=\"${boss.preroomId}\"/>\n`:''
    part2+=boss.startTriggers.includes('roomChange')?`    <StartTrigger type=\"AddressChange\" addressName=\"RoomId\" targetValue=\"${boss.startRoomID}\"/>\n`:''
    part2+=boss.startTriggers.includes('restart')?`    <StartTrigger type=\"GameRestart\"/>\n`:''
    part2+=boss.startTriggers.includes('shootSave')?`    <StartTrigger type=\"GameSave\" roomId="${boss.startSaveRoomId}" left=\"-1000\" top=\"-1000\" right=\"1000\" bottom=\"1000\"/>\n`:''
    if (bossData[i])for (let j=0;j<bossData[i].length;j++){
      if (bossData[i][j]){
        if (bossData[i][j+1])
        part2+=
`
    <Attack name=\"${bossData[i][j].name}\" icon=\"${bossData[i][j].icon}">
      <Time end=\"${bossData[i][j+1].beginTime}\" progressDelay=\"${bossData[i][j].delay===-1?0:bossData[i][j].delay}\"/>
`
        else{
          part2+=
`
    <Attack name=\"${bossData[i][j].name}\" icon=\"${bossData[i][j].icon}">
`

        part2+=boss.endTrigger!=='roomChange'?'':
`
      <Progress type=\"time\" end=\"${boss.bgmLength}\" progressDelay=\"${bossData[i][j].delay===-1?0:bossData[i][j].delay}\"/>   
      <EndTrigger type=\"AddressChange\" addressName=\"RoomId\" targetValue=\"${boss.endRoomID}\"/>
`
        part2+=boss.endTrigger!=='timeOut'?'':`        <Time end=\"${boss.bgmLength}\"/>\n`
        part2+=boss.endTrigger!=='shootSave'?'':
`
      <Progress type=\"time\" end=\"${boss.bgmLength}\" progressDelay=\"${bossData[i][j].delay===-1?0:bossData[i][j].delay}\"/>
      <EndTrigger type=\"GameSave\" roomId="${boss.endSaveRoomId}" left=\"-1000\" top=\"-1000\" right=\"1000\" bottom=\"1000\"/>
`       
        //part2+="      </Attack>\n"
        }
        for(let k=0;k<bossData[i][j].elements.length;k++)
        if (bossData[i][j].elements[k] && k+1<bossData[i][j].elements.length){
          part2+=
`
      <Attack name=\"${bossData[i][j].elements[k].name}\" icon=\"${bossData[i][j].elements[k].icon}\">
        <Time end=\"${bossData[i][j].elements[k+1].beginTime}\" progressDelay=\"${bossData[i][j].elements[k].delay===-1?0:bossData[i][j].elements[k].delay}\"/>
      </Attack>
`
        }else if (bossData[i][j+1] && bossData[i][j+1].elements.length>0){
          part2+=
`
      <Attack name=\"${bossData[i][j].elements[k].name}\" icon=\"${bossData[i][j].elements[k].icon}\">
        <Time end=\"${bossData[i][j+1].elements[0].beginTime}\" progressDelay=\"${bossData[i][j].elements[k].delay===-1?0:bossData[i][j].elements[k].delay}\"/>
      </Attack>
`
        }else if (bossData[i][j+1]){
          part2+=
`
      <Attack name=\"${bossData[i][j].elements[k].name}\" icon=\"${bossData[i][j].elements[k].icon}\">
        <Time end=\"${bossData[i][j+1].beginTime}\" progressDelay=\"${bossData[i][j].elements[k].delay===-1?0:bossData[i][j].elements[k].delay}\"/>
      </Attack>
`
        }else{
          part2+=
`
      <Attack name=\"${bossData[i][j].elements[k].name}\" icon=\"${bossData[i][j].elements[k].icon}\">
`
        part2+=boss.endTrigger!=='roomChange'?'':
`
      <Progress type=\"time\" end=\"${boss.bgmLength}\" progressDelay=\"${bossData[i][j].elements[k].delay===-1?0:bossData[i][j].elements[k].delay}\"/>
      <EndTrigger type=\"AddressChange\" addressName=\"RoomId\" targetValue=\"${boss.endRoomID}\"/>
`
        part2+=boss.endTrigger!=='timeOut'?'':`        <Time end=\"${boss.bgmLength}\" progressDelay=\"${bossData[i][j].elements[k].delay===-1?0:bossData[i][j].elements[k].delay}\"/>\n`
        part2+=boss.endTrigger!=='shootSave'?'':
`
      <Progress type=\"time\" end=\"${boss.bgmLength}\" progressDelay=\"${bossData[i][j].elements[k].delay===-1?0:bossData[i][j].elements[k].delay}\"/>
      <EndTrigger type=\"GameSave\" roomId="${boss.endSaveRoomId}" left=\"-1000\" top=\"-1000\" right=\"1000\" bottom=\"1000\"/>
`       
        part2+="      </Attack>\n"
        }
        
      }
        part2+="    </Attack>\n"
      }
      part2+=
`
  </Boss>
`
    }
    
    console.log(part2)
    const xmlstr=part_1+part2+
`
</Fangame>
`
    console.log(xmlstr)
    
  const configDirPath = $global.$globalSetting.value.exportPath+"\\export\\"+$global.$deadSplitData.value.title;
  const configFilePath = `${configDirPath}\\layout.xml`;


    try {
    if (await exists(configFilePath)) {
        await writeTextFile(configFilePath,xmlstr);
    }
    else{
        if (!await exists(configDirPath)) {
          await mkdir(configDirPath, { recursive: true });
        }
      await writeTextFile(configFilePath, xmlstr);
    }
    
    
    ElMessage.success(`设置已保存`);
  } catch (error) {
    console.error('保存设置失败:', error);
    ElMessage.error(`保存设置失败: ${error}`);
  }

}
const loadXML=()=>{
   ElMessage.info(`开发中...`);
}
//<Boss name=\"\">
  /* let xmlDoc = document.implementation.createDocument("", "", null);
  let root = xmlDoc.createElement("Fangame");
  root.setAttribute("title", `${data.title}`);
    let addressSpace = xmlDoc.createElement("addressSpace");
      let rid=xmlDoc.createElement("RoomId");
      rid.setAttribute("type", `fixed`);
      rid.setAttribute("valueType", `int32`);
      rid.textContent=`${data.roomAddress}`;
      addressSpace.appendChild(rid);
  root.appendChild(addressSpace);
  xmlDoc.appendChild(root);
  let serializer = new XMLSerializer();


  let xmlString = serializer.serializeToString(xmlDoc);


  console.log(xmlString); */



</script>

<style scoped>
.export-btn {
  cursor: pointer;
  color: #606266;
  /* Element 默认文字色 */
  padding: 4px 8px;
  border-radius: 4px;
  transition: color 0.2s, background-color 0.2s;
  display: flex;
  align-items: center;

}

.export-btn:hover {
  color: #409eff;
  /* Element 主色 */
  background-color: #ebedf2;
  /* hover 背景色 */
}

.main-container {
  border: 3px solid #E6E8EB;
  border-radius: 10px;
  overflow: hidden;
}

.layout-container-demo .el-header {
  position: relative;
  background-color: var(--el-color-primary-light-7);
  color: var(--el-text-color-primary);
}

.layout-container-demo .el-col {
  color: var(--el-text-color-primary);
  background:
    /* var(--el-color-primary-light-8) */
    #E6E8EB;
}

.layout-container-demo .el-menu {
  border-right: none;
}

.layout-container-demo .el-main {
  padding: 0;
}

.layout-container-demo .toolbar {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  right: 20px;
}

.el-row .el-col {
  height: 100%;
}

.el-table {
    height: 100%;
}
.bossname{
  margin-left: 10px;

  font-weight: bold;
  color: #8aadaa;
}

.el-dialog__body {
  padding: 0px 20px 20px 20px;
}

.el-dialog__header {
  padding: 20px 20px 10px 20px;
}

.el-dialog__title {
  font-size: 20px;
  font-weight: bold;
}

.el-dialog__headerbtn {
  top: 20px;
  right: 20px;
}

::v-deep .el-dialog {
display: flex;
flex-direction: column;
margin: 0 !important;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
max-height: calc(100% - 30px);

}

::v-deep .el-dialog__body {
flex: 1;
overflow: auto;
}
</style>